<?php
/**
 * Created by PhpStorm.
 * User: 17274
 * Date: 2018/3/27
 * Time: 21:06
 */
namespace app\admin\model;

use app\admin\helper\DBhelper;
use app\admin\helper\LangHelper;
use app\admin\helper\SearchHelper;
use app\admin\popo\LayData;
use think\Config;
use think\Session;
use think\Validate;

class RoleM extends  BaseM
{
    protected $table = 'tb_role';
    protected $module = '权限控制';

    /*
     * rule
     * 验证data
     * @params $data
     * 新增和修改时验证
     * */
    public function validate_model($scene){
        $post = input('post.');
        $rule = [
        ];
        $msg = [
            'name.require' => '__role.validata.name.require__',
            'name.chsAlpha' => '__role.validata.name.chsAlpha__'
        ];
        if ($scene=="edit"){
            $rule['name']='require|chsAlpha';
        }else if ($scene=="add"){
            $rule['name']='unique:role|require|chsAlpha';
            $msg['name.unique']='__role.validata.name.unique__';
        }
        $msg = LangHelper::convertLang($msg,'field');
        $validate = new Validate($rule, $msg);
        $result = $validate->check($post);
        if(!$result){
            return op_msg(0,$validate->getError());
        }
        return op_msg(1,'success');
    }

    /**
     * 前端search控件
     * button vale [ add edit del search export ]
     * @return mixed
     */
    public function __search(){
        $search = [
            'tag'=>['field'=>'tag','title'=>'__tag__','type'=>'input','value'=>''],
            'status'=>['field'=>'status','title'=>'__status__','type'=>'select','value'=>'function:getStatusList'],
            'created_at'=>['field'=>'created_at','title'=>'__created_at__','type'=>'date_range','value'=>'function:getMonthDateRange'],
            'button'=>['type'=>'button','value'=>['add','search','export']],
        ];
        SearchHelper::convertValue($search);
        $search['form'] = implode(',',array_keys($search));
        return LangHelper::convertLang($search,'field');
    }

    /**
     * 前端表格列
     * @return string
     */
    public function __header(){
        $header = [
            ['type'=>'checkbox'],
            ['field'=>'name','title'=>'__role.name__'],
            ['field'=>'role_id','title'=>'__role.role_id__'],
            ['field'=>'status','title'=>'__status__','style'=>'text-align:center'],
            ['field'=>'created_at','title'=>'__created_at__'],
            ['field'=>'updated_at','title'=>'__updated_at__'],
            ['field'=>'op','title'=>'__op__','toolbar'=>'#operate']
        ];
        return json_encode(LangHelper::convertLang($header,'field'));
    }

    /*
     * 列表
     * */
   public function listData(){
       $page=input("post.page/d");
       $limit=input("post.limit/d");
       $tag=input("post.tag/s");
       $status=input("post.status/d");
       if ($status==0)
           $status = [1,2];
       $time=input("post.created_at/s");
       $start = strtotime(explode(' - ',$time)[0]);
       $end = strtotime(explode(' - ',$time)[1]);

       $where = [
           'name|role_id'=>['like',"%".$tag."%"],
           'created_at'=>['between', [$start, $end+86399]],
           'status' =>['in',$status]
       ];

       //非admin用户不能看到超级管理员信息
       if (Session::get("username") != 'admin') {
           $where['role_id'] =  array('<>','1c6a0a166759b291ec74644bdb25123c');
       }

       $log = [
           'op_uid' => Session::get('username'),
           'op_module' => $this->module,
           'op_type' => 'search',
           'op_origin' => $this->table,
           'op_data' => json_encode($where,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
           'op_ip' => getIP(),
       ];
       //export逻辑
       if (input("post.export/b")) {
           $header = json_decode($this->__header(),true);
           $export_data = $this->where($where)->order('id desc')->select()->toArray();
           $log['op_sql'] = $this->getLastSql();
           $log['op_type'] = 'export';
           $log['op_data'] = json_encode($header,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
           LogsM::add($log);
           pr_log($log,'operate');
           export('角色列表',$export_data,$header);
       }

       $resp = new LayData();
       $resp->count = $this->where($where)->count();
       $resp->data = $this->where($where)->order('id desc')->page($page,$limit)->select();
       $resp->extra_data = Config::get('app_debug')?$this->getLastSql():'';
       $log['op_sql'] = $this->getLastSql();
       LogsM::add($log);
       pr_log($log,'operate');
       return $resp;
   }

    /**
     * list All Data  status=1
     * @return false|\PDOStatement|string|\think\Collection
     */
   public function listAll(){
       //非admin用户不能看到超级管理员信息
       if (Session::get("username") != 'admin') {
           $where['role_id'] =  array('<>','1c6a0a166759b291ec74644bdb25123c');
       }
       $where['status'] = 1;
       return $this->where($where)->order('id desc')->select();
   }

    /*
     * 新增
     * */
    public function add(){
        $data=input('post.');
        unset($data['method']);
        $data['created_at']=time();
        $data['updated_at']=time();
        $data['role_id']=md5(time());
        $re = $this->save($data);
        $last_sql = Config::get('app_debug')?$this->getLastSql():'';
        if($re){
            $log = [
                'op_uid' => Session::get('username'),
                'op_module' => $this->module,
                'op_type' => 'add',
                'op_origin' => $this->table,
                'op_data' => $data['name'],
                'op_ip' => getIP(),
                'op_sql' => $this->getLastSql(),
            ];
            LogsM::add($log);
            pr_log($log,'operate');
            return op_success($last_sql);
        }
        return op_fail($last_sql);
    }

    /*
     * 修改
     * */
    public function edit(){
        $data=input('post.');
        $id=$data['id'];
        unset($data['method']);
        //只修改变化字段
        $origin = $this->getById($id)->toArray();
        $data = DBhelper::getChangeData($data,$origin);
        if (!empty($data)){
            $data['updated_at']=time();
            $re = $this->where('id',$id)->update($data);
            $last_sql = Config::get('app_debug')?$this->getLastSql():'';
            if($re){
                $log = [
                    'op_uid' => Session::get('username'),
                    'op_module' => $this->module,
                    'op_type' => 'edit',
                    'op_origin' => $this->table,
                    'op_data' => json_encode($data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
                    'op_ip' => getIP(),
                    'op_sql' => $this->getLastSql(),
                ];
                LogsM::add($log);
                pr_log($log,'operate');
                return op_success($last_sql);
            }
            return op_fail($last_sql);
        }
        return op_nochange();
    }

    /*
     * 删除
     * */
    public function del(){
        $ids=input('post.ids/a');
        $role_ids=input('post.role_ids/a');
        $op_names=input('post.names/a');
        //事务开始
        $this->startTrans();
        $re = $this->destroy($ids);
        $last_sql = Config::get('app_debug')?$this->getLastSql():'';
        $last_sql_1 = $this->getLastSql();
        if ($re){
            //删除对应role_id的resource
            if (ResourceM::del($role_ids) && ResourceButtonM::del($role_ids)) {
                $this->commit();
                $op_data = [
                    'roleName' =>$op_names,
                    'delResourceRoleid' => $role_ids
                ];
                $log = [
                    'op_uid' => Session::get('username'),
                    'op_module' => $this->module,
                    'op_type' => 'delete',
                    'op_origin' => $this->table,
                    'op_data' => json_encode($op_data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
                    'op_ip' => getIP(),
                    'op_sql' => $last_sql_1,
                ];
                LogsM::add($log);
                pr_log($log,'operate');
                return op_success($last_sql);
            }
        }
        $this->rollback();
        return op_fail($last_sql);
    }

    /*
     * 根据ID信息
     * */
    public function getByRoleId($role_id){
        return $this->where(["role_id"=>$role_id])->find();
    }

}